<template>
  <div>
    <!-- 表单 -->
    <Form :model="dayForm" style="display: block;">
      <Row gutter="40">
        <i-col span="6">
          <FormItem>
              <Cascader change-on-select :data="organizationList" v-model="dayForm.organization" @on-change="organizationChange" placeholder="所属机构" clearable></Cascader>
          </FormItem>
        </i-col>
        <i-col span="6">
          <FormItem>
            <Select v-model="dayForm.empolyee" placeholder="员工" :clearable="isClearable">
              <Option
                v-for="item in empolyeeList"
                :key="item.key"
                :value="item.key"
              >{{item.value}}-{{item.key}}</Option>
            </Select>
          </FormItem>
        </i-col>
        <i-col span="6">
          <FormItem>
            <DatePicker
              type="daterange"
              placeholder="开始时间~结束时间"
              :editable="false"
              style="width:100%"
              v-model="dayForm.dateRange"
            ></DatePicker>
          </FormItem>
        </i-col>
        <i-col span="6">
          <FormItem>
            <Select v-model="dayForm.role" placeholder="所属角色" :clearable="isClearable">
              <Option v-for="item in roleList" :key="item.key" :value="item.key">{{item.value}}</Option>
            </Select>
          </FormItem>
        </i-col>
      </Row>
      <Row>
        <FormItem>
          <Button type="primary" style="margin-right:20px" @click="handleSubmit(1)">查询</Button>
          <Button @click="handleReset()" :disabled="resetButtonDisabled">重置</Button>
        </FormItem>
      </Row>
    </Form>

    <!-- 查询数据 -->
    <Table :columns="dayColumns" :data="dayData">
      <template slot-scope="{row}" slot="applyNo">
        <a @click="outgoOrder(row)">{{row.applyNo}}</a>
      </template>
      <template slot-scope="{row}" slot="record">
        <a @click="offWork='true';currentRow = row;outsideDetail(row)">查看</a>
      </template>
    </Table>

    <!-- 分页 -->
    <Page
      :total="total"
      show-sizer
      show-total
      style="text-align:right;margin-top:20px;margin-bottom:30px;"
      @on-change="pageChange"
      @on-page-size-change="pageSizeChange"
      :page-size-opts="pageSizeOptions"
      :current="pageIndex"
      :page-size="pageSize"
      transfer
    ></Page>

    <!-- 当日外出打卡记录对话窗口 -->
    <div class="dayCalModal">
      <Modal
        footer-hide="true"
        :value="offWork"
        :mask-closable="false"
        @on-visible-change="modalVisibleChange"
        @on-cancel="modalCancel"
        width="1000"
      >
        <span
          slot="header"
          style="color:#fff;font-size:16px"
        >{{currentRow.signDay}}&nbsp;&nbsp;外出打卡记录</span>
        <div class="modalContent">
          <div class="image">
            <!-- <img :src="headPortrait" /> -->
          </div>
          <div class="baseContent">
            <div class="name">{{currentRow.name}}</div>
            <div class="otherContent">
              所属机构：{{currentRow.organizations}}
              <span style="margin-left:5px;margin-right:5px;">|</span>
              角色：{{currentRow.role}}
            </div>
          </div>
        </div>
        <span style="display:block;clear:both"></span>
        <Table :columns="outColumns" :data="outData">
          <template slot="photoUrl" slot-scope="{row}">
            <span v-for="(item,index) in row.photoUrl" :key="index" class="showSmallPhoto">
              <span v-if="item">
                <span v-if="item[1] === '0'">
                  <video :src="item[0]" @click="showPhoto(item)"></video>
                </span>
                <span v-if="item[1] === '1'">
                  <img :src="item[0]" @click="showPhoto(item)" />
                </span>
              </span>
            </span>
          </template>
        </Table>
      </Modal>
    </div>
    <Modal
      footer-hide="true"
      :value="photoModal"
      :mask-closable="true"
      @on-visible-change="modalVisibleChange2"
      :closable="false"
    >
      <span v-if="photoItem[1] === '0'">
        <span class="photoModal">
          <video ref="video" :src="photoItem[0]" controls id="video1" controlslist="nodownload" />
        </span>
      </span>
      <span v-if="photoItem[1] === '1'">
        <span class="photoModal">
          <img :src="photoItem[0]" />
        </span>
      </span>
    </Modal>
  </div>
</template>

<script>
import {exportFile} from "../../../util/util"
import util from "../../../util/util"
export default {
  name:"dayCal",
  props: {
    dayPass: {
      type: String
    }
  },
  data() {
    return {
      dayForm: {
        organization: "",
        empolyee: "",
        dateRange: ["", ""],
        role: ""
      },
      organizationList: [],
      empolyeeList: [],
      roleList: [],
      dayColumns: [
        {
          title: "日期",
          key: "signDays",
          fixed: "left",
          width: "150"
        },
        {
          title: "姓名",
          key: "name",
          fixed: "left",
          width: "150"
        },
        {
          title: "工号",
          key: "no",
          align: "center",
          width: "150"
        },
        {
          title: "所属机构",
          key: "organizations",
          width: "260"
        },
        {
          title: "角色",
          key: "role",
          width: "120"
        },
        {
          title: "关联外出单",
          key: "applyNo",
          align: "center",
          width: "",
          slot: "applyNo"
        },
        {
          title: "当日外出打卡记录",
          key: "record",
          align: "center",
          width: "",
          slot: "record"
        }
      ],
      dayData: [],
      currentRow: "",
      offWork: false,
      total: 0,
      pageIndex: 1,
      pageSize: 10,
      pageSizeOptions: [5, 10, 15, 20],
      outColumns: [
        {
          title: "打卡时间",
          key: "signTime",
          align: "center",
          width: "120"
        },
        {
          title: "打卡地点",
          key: "signSite",
          width: "300"
        },
        {
          title: "设备",
          key: "equipment",
          width: "300"
        },
        {
          title: "打卡照片",
          key: "photoUrl",
          slot: "photoUrl"
        }
      ],
      outData: [],
      isClearable: true,
      resetButtonDisabled: false,
      pageObj: "",
      // 打卡照片
      photoModal: false,
      photoItem: "",
      // 头像
      headPortrait: ""
    };
  },
  methods: {
    // 点击照片缩略图触发事件
    showPhoto(photoUrl) {
      this.photoModal = true;
      this.photoItem = photoUrl;
      // this.$refs.showBigPhoto.src = photoUrl;
    },

    // 照片窗口
    modalVisibleChange2(value) {
      // if (this.photoItem[1] === "0") {
      //   this.$refs.video["disablePictureInPicture"] = true;
      // }
      if (!value) {
        this.photoModal = false;
        let video1 = document.getElementById("video1");
        video1.pause();
      }
    },

    // 重置
    handleReset() {
      this.dayForm = {
        organization: "",
        empolyee: "",
        dateRange: ["", ""],
        role: ""
      };
      this.dayData = []
    },

    // 提交
    handleSubmit(e) {
      // this.pageIndex = 1;
      this.pageSize = 10;
      if (
        !this.dayForm.organization &&
        !this.dayForm.empolyee &&
        !this.dayForm.dateRange[0] &&
        !this.dayForm.role &&
        !this.dayForm.attendStatus
      ) {
        this.$Message.error("请至少选择一个条件");
        return;
      }
      let startDate = "";
      let endDate = "";
      if (this.dayForm.dateRange[0]) {
        let date1 = new Date(this.dayForm.dateRange[0]).toJSON();
        startDate = new Date(+new Date(date1) + 8 * 3600 * 1000).toISOString();
        let date2 = new Date(this.dayForm.dateRange[1]).toJSON();
        endDate = new Date(+new Date(date2) + 8 * 3600 * 1000).toISOString();
      }
      let obj = {
        organizationNo: this.dayForm.organization[this.dayForm.organization.length-1],
        no: this.dayForm.empolyee,
        beginTime: startDate,
        finishTime: endDate,
        roleNo: this.dayForm.role,
        index: e === 1 ? this.pageIndex = 1 : this.pageIndex,
        pageSize: this.pageSize
      };
      this.pageObj = obj;
      this.$router.push({
        path: this.$router.path,
        query: this.pageObj
      })
      this.api.outsideByDay(obj).then(res => {
        if (res.code == 200 && res.data != null) {
          this.$emit("modifyDayFlag", false);
          this.total = res.data.total;
          this.dayData = [];
          res.data.records.forEach(element => {
            if (element.organizationNo && element.organization) {
              element.organizations =
                element.organizationNo + "-" + element.organization;
            }
            if (element.signDay) {
              element.signDays =
                element.signDay.substr(2, 8) +
                "星期" +
                "天一二三四五六".charAt(new Date(element.signDay).getDay());
            }
            this.dayData.push(element);
          });
          this.$Message.info(res.msg);
        } else {
          this.$emit("modifyDayFlag", true);
          this.dayData = [];
          this.total = 0;
          this.$Message.info(res.msg);
        }
      });
    },

    // 页面查询
    pageSubmit() {
      this.pageObj.index = this.pageIndex;
      this.pageObj.pageSize = this.pageSize;
      this.$router.push({
        path: this.$router.path,
        query: this.pageObj
      })
      this.api.outsideByDay(this.pageObj).then(res => {
        if (res.code == 200 && res.data != null) {
          this.total = res.data.total;
          this.dayData = [];
          res.data.records.forEach(element => {
            if (element.organizationNo && element.organization) {
              element.organizations =
                element.organizationNo + "-" + element.organization;
            }
            if (element.signDay) {
              element.signDays =
                element.signDay.substr(2, 8) +
                "星期" +
                "天一二三四五六".charAt(new Date(element.signDay).getDay());
            }
            this.dayData.push(element);
          });
        } else {
          this.dayData = [];
          this.total = 0;
          this.$Message.info(res.msg);
        }
      });
    },

    // 对话框关闭设置
    modalVisibleChange(bool) {
      if (bool == false) {
        this.offWork = false;
      }
    },

    // 分页设置
    pageChange(pageIndex) {
      this.pageIndex = pageIndex;
      this.pageSubmit();
    },
    pageSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.pageSubmit();
    },

    // 外出详情信息
    outsideDetail(row) {
      let obj = {
        no: row.no,
        signDay: row.signDay
      };
      this.api.getOnesDetail(obj).then(res => {
        if (res.code == 200 && res.data != null) {
          this.outData = res.data;
          this.outData.forEach(element => {
            if (element.signTime) {
              element.signTime = element.signTime.substr(0, 5);
            }
          });
        } else {
          this.$Message.info(res.msg);
        }
      });
      this.headPortrait = "";
      this.api.getUserChatHeadByNo(obj).then(res => {
        if (res.code == 200 && res.data != null) {
          this.headPortrait = res.data;
        }
      });
    },

    // 关闭对话框
    modalCancel() {
      this.outData = [];
    },

    // 跳转至详情页面
    outgoOrder(row) {
      // this.$emit("tabsType","day")
      sessionStorage.setItem("tabsType" ,"day")
      console.log("跳转");
      // return
      this.$router.push({
        path: "/U/systemManagement/approvalDetails",
        query: {
          item: row
        }
      });
    },

    // 导出报表
    exportExcel() {
      if (
        !this.dayForm.organization &&
        !this.dayForm.empolyee &&
        !this.dayForm.dateRange[0] &&
        !this.dayForm.role &&
        !this.dayForm.attendStatus
      ) {
        this.$Message.error("请至少选择一个条件");
        return;
      }
      let startDate = "";
      let endDate = "";
      if (this.dayForm.dateRange[0] != "") {
        let date1 = new Date(this.dayForm.dateRange[0]).toJSON();
        startDate = new Date(+new Date(date1) + 8 * 3600 * 1000).toISOString();
        let date2 = new Date(this.dayForm.dateRange[1]).toJSON();
        endDate = new Date(+new Date(date2) + 8 * 3600 * 1000).toISOString();
      }
      let obj = {
        organizationNo: this.dayForm.organization[this.dayForm.organization.length-1],
        no: this.dayForm.empolyee,
        beginTime: startDate,
        finishTime: endDate,
        roleNo: this.dayForm.role,
        loginNo: sessionStorage.getItem("useragentcode")
      };
      // let url = "../rest/export/uerOutsideExport";
      exportFile("scrm-gateway/scrm-uer/api/export/uerOutsideExport",obj)
      // window.open(
      //   url +
      //     "?organizationNo=" +
      //     obj.organizationNo +
      //     "&no=" +
      //     obj.no +
      //     "&beginTime=" +
      //     obj.beginTime +
      //     "&finishTime=" +
      //     obj.finishTime +
      //     "&roleNo=" +
      //     obj.roleNo +
      //     "&loginNo=" +
      //     obj.loginNo
      // );
    },

    // 获取当前机构及以下
    getOrganizationList() {
      this.api.remanagecomList().then(res => {
        if (res.code == 200 && res.data != null) {
          let arr = []
          arr.push(res.data)
          arr.forEach(one=>{
            one.value = one.comcode
            one.label = one.comcode + '-' + one.name
            one.children = one.chilDren || []
            if (one.children) {
              one.chilDren.forEach(two=>{
                two.value = two.comcode
                two.label = two.comcode + '-' + two.name
                two.children = two.chilDren || []
                if (two.children) {
                  two.children.forEach(three=>{
                    three.value = three.comcode
                    three.label = three.comcode + '-' + three.name
                    three.children = three.chilDren || []
                    if (three.children) {
                      three.children.forEach(four=>{
                        four.value = four.comcode
                        four.label = four.comcode + '-' + four.name
                        four.children = four.chilDren || []
                      })
                    }
                  })
                }
              })
            }
          })
          console.log(arr);
          this.organizationList = arr
          // this.Echo()
        } else {
          this.organizationList = [];
        }
      });
      this.api.organizationDict().then(res => {
        if (res.code == 200 && res.data != null) {
          let a = JSON.stringify(res.data[0].map);
          if (a !== "{}") {
            let b = a.substr(1, a.length - 2);
            let c = b.split(",");
            c.forEach(element => {
              let d = element.split(":");
              this.roleList.push({
                key: d[0].replace(/\"/g, ""),
                value: d[1].replace(/\"/g, "")
              });
            });
          }
          // if (res.data[0].listKeyValueVOS.length > 0) {
          //   this.organizationList = res.data[0].listKeyValueVOS;
          // }
          // 角色是外勤的处理
          if (this.roleList.length == 1 && this.roleList[0].key == 1) {
            this.isClearable = false;
            this.resetButtonDisabled = true;
            this.dayForm.organization = this.organizationList[0].value;
            this.organizationChange([this.dayForm.organization]);
            this.dayForm.role = this.roleList[0].key;
          }
        } else {
          this.$Message.error(res.msg);
        }
      });
    },
    Echo(){
      this.jsonData = util.GetRequest(decodeURI(location.hash)) || {}
      console.log(this.jsonData,"404")
      if(this.jsonData.endTime || this.jsonData.starTime || this.jsonData.uNo || this.jsonData.status || this.jsonData.uRole || (this.jsonData.index || this.pageIndex != "1")){
      console.log("来了");
      this.dayForm.role = this.jsonData.roleNo  //角色
      // 开始时间-结束时间
      let arr1 = []
      arr1.push(this.jsonData.starTime,this.jsonData.endTime)
      this.dayForm.dateRange = arr1
      //所属机构
        let arr = []
        this.organizationList.forEach(one =>{
          if(one.value == this.jsonData.organizationNo){
            arr.push(one.value)
          }else if(one.children){
            one.children.forEach(tow =>{
              if(tow.value == this.jsonData.organizationNo){
                arr.push(one.value,tow.value)
              }else if(tow.children){
                tow.children.forEach(three =>{
                  if(three.value == this.jsonData.organizationNo){
                    arr.push(one.value,tow.value,three.value)
                  }else if(three.children){
                    three.children.forEach(four =>{
                      if(three.value == this.jsonData.organizationNo){
                        arr.push(one.value,tow.value,three.value,four.value)
                      }
                    })
                  }
                })
              }
            })
          }
        })
        this.dayForm.organization = arr
        this.pageIndex = parseInt(this.jsonData.index)
        this.organizationChange(this.dayForm.organization)
        this.$nextTick(()=>{
          this.dayForm.empolyee = this.jsonData.no//员工
          this.handleSubmit()
        })
      }else{
        console.log('没来');
        // this.handleSubmit()
      }
    },
    // 机构改变，查询员工
    organizationChange(value) {
      if (value) {
        this.dayForm.empolyee = "";
        if (value) {
          let obj = {
            managecom: value
          };
          $.ajax("scrm-gateway/scrm-uer/api/uerList/selectuser/" + value[value.length-1], {
            method: "get",
            contentType: "application/json;charset=utf-8",
            beforeSend: function(xhr) {
              xhr.setRequestHeader(
                "Authorization",
                sessionStorage.getItem("credentials")
              );
            },
            success: res => {
              if (res.data.length > 0) {
                this.empolyeeList = res.data;
                // 角色是外勤时，固定人员
                if (this.roleList.length == 1 && this.roleList[0].key == 1) {
                  this.dayForm.empolyee = this.empolyeeList[0].key;
                }
              } else {
                this.empolyeeList = [];
              }
            },
            error: res => {
              this.$Message.error(res.msg);
            }
          });
        }
      } else {
        this.empolyeeList = [];
        this.dayForm.empolyee = "";
      }
    }
  },
  watch: {
    dayPass: function(val, oldVal) {
      this.exportExcel();
    }
  },
  mounted() {
  },
  beforeMount() {
    this.getOrganizationList();
  },
  beforeDestroy(){
    this.dayForm = null;
    this.organizationList = null;
    this.empolyeeList = null;
    this.roleList = null;
    this.dayColumns = null;
    this.dayData = null;
    this.currentRow = null;
    this.offWork = null;
    this.total = null;
    this.pageIndex = null;
    this.pageSize = null;
    this.pageSizeOptions = null;
    this.outColumns = null;
    this.outData = null;
    this.isClearable = null;
    this.resetButtonDisabled = null;
    this.pageObj = null;
    this.photoModal = null;
    this.photoItem = null;
    this.headPortrait = null;
  }
};
</script>

<style lang="less" scoped>
@import "./dayCount.less";
</style>

<style>
.ivu-modal-header {
  background-color: #2d8cf0;
}
.ivu-modal-close .ivu-icon-ios-close {
  color: #fff !important;
}
</style>